﻿using brevis.Nop.BusinessLogic.Reports;
using NopSolutions.NopCommerce.BusinessLogic;
using NopSolutions.NopCommerce.BusinessLogic.SEO;
using System;
using System.Web;

namespace brevis.Nop.BusinessLogic.Reports
{
    public class HttpHandler : IHttpHandler
    {
        /// <summary>
        /// You will need to configure this handler in the Web.config file of your 
        /// web and register it with IIS before being able to use it. For more information
        /// see the following link: http://go.microsoft.com/?linkid=8101007
        /// </summary>
        #region IHttpHandler Members

        public bool IsReusable
        {
            // Return false in case your Managed Handler cannot be reused for another request.
            // Usually this would be false in case you have some state information preserved per request.
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            var rs = new ReportService(NopContext.Current, HttpContext.Current);
            byte[] reportPDFBytes = null;
            try
            {
                reportPDFBytes = rs.GetLocalReportBytes(
                    HttpContext.Current.Request.QueryString["reportid"]);

            }
            catch (UnauthorizedAccessException)
            {
                string loginURL = SEOHelper.GetLoginPageUrl(true);
                HttpContext.Current.Response.Redirect(loginURL);
            }

            HttpContext.Current.Response.ContentType = "application/pdf";
            HttpContext.Current.Response.AddHeader("Expires", "0");
            HttpContext.Current.Response.AddHeader("Cache-Control", "max-age=0");
            HttpContext.Current.Response.AddHeader("Content-disposition", "inline; filename=report.pdf");
            HttpContext.Current.Response.BinaryWrite(reportPDFBytes);
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();
        }

        #endregion
    }
}
